<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入活动名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="活动时间" prop="activeDate">
            <el-date-picker
              v-model="formData.activeDate"
              type="datetime"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              placeholder="选择活动时间"
              class="w100%!"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="男人数" prop="menNum">
            <el-input v-model="formData.menNum" placeholder="请输入男人数" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="女人数" prop="womenNum">
            <el-input v-model="formData.womenNum" placeholder="请输入女人数" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formType === 'create'">
          <el-form-item label="活动商品" prop="packageProductRespVOList">
            <el-button :icon="CirclePlus" @click="handleSelectGoods" class="ml3"
              >选择商品</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="活动费用/人" prop="activeCost">
            <el-input v-model="formData.activeCost" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止时间" prop="deadline">
            <el-date-picker
              v-model="formData.deadline"
              type="datetime"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              placeholder="选择活动时间"
              class="w100%!"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="活动描述" prop="activeDesc">
            <el-input
              type="textarea"
              v-model="formData.activeDesc"
              :rows="3"
              placeholder="请输入活动描述"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 头像 -->
          <el-form-item label="活动封面" prop="activeCover">
            <UploadImg v-model="formData.activeCover" :limit="1" :is-show-tip="false" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 商品内容 -->
      <div class="mb5">商品内容：</div>
      <el-table :data="formData.packageProductRespVOList" style="width: 100%">
        <el-table-column prop="productName" label="商品名称" align="center" />
        <el-table-column prop="merchantName" label="所属商家" align="center" />
        <el-table-column prop="address" label="地址" align="center" width="300px" />
        <el-table-column prop="supplyPrice" label="供货价/总" align="center" />
        <el-table-column prop="platformPrice" label="平台售价/人" align="center" />
        <el-table-column prop="productIntroduct" label="商品介绍" align="center">
          <template #default="scope">
            <el-popover
              :width="300"
              popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
            >
              <template #reference>
                <span class="color-blue">查看</span>
              </template>
              <template #default>
                {{ scope.row.productIntroduct }}
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right" width="60">
          <template #default="scope">
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.productId)"
              v-hasPermi="['blind:activity-info:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>

    <!-- 成立弹窗：查看 -->
    <Packages ref="formRefPackages" @child-event="handleChildEvent" />
  </Dialog>
</template>
<script setup lang="ts">
import * as ActivityInfoApi from '@/api/blind/activityInfo'
import Packages from './components/Packages.vue'
import { CirclePlus } from '@element-plus/icons-vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  name: undefined,
  activeDate: undefined,
  activeTimeBegin: undefined,
  activeTimeEnd: undefined,
  menNum: undefined,
  womenNum: undefined,
  head: undefined,
  packageType: undefined,
  packageName: undefined,
  activeCost: 0,
  deadline: undefined,
  activeDesc: undefined,
  activeCover: undefined,
  auditStatus: undefined,
  auditUser: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }],
  packageType: [{ required: true, message: '套餐类型不能为空', trigger: 'blur' }],
  suitActivity: [{ required: true, message: '适应活动不能为空', trigger: 'blur' }],
  packageProductRespVOList: [{ required: true, message: '商品不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '套餐价格不能为空', trigger: 'blur' }],
  deadline: [{ required: true, message: '截止时间不能为空', trigger: 'blur' }],
  activeCover: [{ required: true, message: '活动封面不能为空', trigger: 'blur' }],
  auditStatus: [
    { required: true, message: '审核状态（0未审核 1已通过 2已驳回）不能为空', trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref

// 商品列表
const goodsList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ActivityInfoApi.getActivityInfo(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  // formData.value.packageProductRespVOList = goodsList.value
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ActivityInfoApi.ActivityInfoVO
    if (formType.value === 'create') {
      await ActivityInfoApi.createActivityInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await ActivityInfoApi.updateActivityInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 选择商品
const formRefPackages = ref()
const handleSelectGoods = () => {
  formRefPackages.value.open()
}

// 父组件回调事件
const handleChildEvent = (dataFromChild) => {
  formData.value.packageProductRespVOList = dataFromChild

  let totalPrice = 0
  formData.value.packageProductRespVOList.forEach((item) => {
    totalPrice += Number(item?.platformPrice)
    return totalPrice
  })

  formData.value.activeCost =  roundToTwoDecimalPlaces(totalPrice);
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 发起删除
    formData.value.packageProductRespVOList = formData.value.packageProductRespVOList.filter(
      (item) => item.productId !== id
    )
  } catch {}
}

// 传入一个数字和需要保留的小数位数，返回四舍五入并保留指定位数的结果
function roundToTwoDecimalPlaces(num: number): number {
  return Math.round(num * 100) / 100;
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: undefined,
    activeDate: undefined,
    activeTimeBegin: undefined,
    activeTimeEnd: undefined,
    menNum: undefined,
    womenNum: undefined,
    head: undefined,
    packageType: undefined,
    packageName: undefined,
    activeCost: 0,
    deadline: undefined,
    activeDesc: undefined,
    activeCover: undefined,
    auditStatus: undefined,
    auditUser: undefined
  }
  formRef.value?.resetFields()
  goodsList.value = []
}
</script>
